/**
 * 租户上下文类
 */
class TenantContext {
	static _currentTenant = null;
	static _currentUser = null;

	// 设置当前租户
	static setCurrentTenant(tenantId) {
		this._currentTenant = tenantId;
	}

	// 获取当前租户
	static getCurrentTenant() {
		if (!this._currentTenant) {
			throw new Error("租户上下文未设置");
		}
		return this._currentTenant;
	}

	// 设置当前用户
	static setCurrentUser(userid) {
		this._currentUser = userid;
	}

	// 获取当前用户
	static getCurrentUser() {
		return this._currentUser;
	}

	// 清除上下文(用于测试或后台任务)
	static clear() {
		this._currentTenant = null;
		this._currentUser = null;
	}

	// 在上下文中执行函数
	static async runInContext(tenantId, userId, fn) {
		const prevTenant = this._currentTenant;
		const prevUser = this._currentUser;
		try {
			this.setCurrentTenant(tenantId);
			this.setCurrentUser(userId);
			return await fn();
		} finally {
			this._currentTenant = prevTenant;
			this._currentUser = prevUser;
		}
	}
}

module.exports = {
    TenantContext: TenantContext
};